import { createRouter, createWebHistory } from 'vue-router'
import Home from '../views/Home.vue'
import { isLoggedIn } from '../api/user'
import { showToast } from 'vant'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      name: 'home',
      component: Home,
      meta: {
        requiresAuth: true
      }
    },
    {
      path: '/login',
      name: 'login',
      component: () => import('../views/Login.vue'),
      meta: {
        requiresAuth: false
      }
    },
    {
      path: '/category',
      name: 'category',
      component: () => import('../views/Category.vue'),
      meta: {
        requiresAuth: true
      }
    },
    {
      path: '/products/:id',
      name: 'products',
      component: () => import('../views/Product.vue'),
      meta: {
        requiresAuth: true
      }
    },
    {
      path: '/product/add',
      name: 'productAdd',
      component: () => import('../views/ProductAdd.vue'),
      meta: {
        requiresAuth: true
      }
    },
    {
      path: '/product/edit/:id',
      name: 'productEdit',
      component: () => import('../views/ProductEdit.vue'),
      meta: {
        requiresAuth: true
      }
    },
    {
      path: '/order/product',
      name: 'orderProduct',
      component: () => import('../views/OrderProduct.vue'),
      meta: {
        requiresAuth: true
      }
    },
    {
      path: '/new-record',
      name: 'NewRecord',
      component: () => import('../views/NewRecord.vue'),
      meta: {
        requiresAuth: true
      }
    },
    {
      path: '/history',
      name: 'History',
      component: () => import('../views/History.vue'),
      meta: {
        requiresAuth: true
      }
    },
    {
      path: '/customer-orders/:date/:customerId',
      name: 'CustomerOrders',
      component: () => import('../views/CustomerOrders.vue'),
      props: true,
      meta: {
        requiresAuth: true
      }
    },
    {
      path: '/settlement',
      name: 'Settlement',
      component: () => import('../views/Settlement.vue'),
      meta: {
        requiresAuth: true
      }
    },
    {
      path: '/customer',
      name: 'Customer',
      component: () => import('../views/Customer.vue'),
      meta: {
        requiresAuth: true
      }
    },
    {
      path: '/customer/add',
      name: 'CustomerAdd',
      component: () => import('../views/CustomerAdd.vue'),
      meta: {
        requiresAuth: true
      }
    },
    {
      path: '/customer/edit/:id',
      name: 'CustomerEdit',
      component: () => import('../views/CustomerEdit.vue'),
      props: true,
      meta: {
        requiresAuth: true
      }
    },
    {
      path: '/customer/detail/:id',
      name: 'CustomerDetail',
      component: () => import('../views/CustomerDetail.vue'),
      props: true,
      meta: {
        requiresAuth: true
      }
    },
    {
      path: '/sales-ranking',
      name: 'SalesRanking',
      component: () => import('../views/SalesRanking.vue'),
      meta: {
        requiresAuth: true
      }
    },
    {
      path: '/bill-preview/:id',
      name: 'BillPreview',
      component: () => import('../views/BillPreview.vue'),
      props: true,
      meta: {
        requiresAuth: true
      }
    },
    {
      path: '/batch-bill-preview',
      name: 'BatchBillPreview',
      component: () => import('../views/BatchBillPreview.vue'),
      meta: {
        requiresAuth: true
      }
    },
  ]
})

// 全局路由守卫
router.beforeEach((to, from, next) => {
  console.log('路由导航:', { from: from.path, to: to.path, auth: isLoggedIn(), token: localStorage.getItem('token') })
  
  // 处理查询参数中的重定向URL
  if (to.path === '/login' && to.query.redirect) {
    let redirect = to.query.redirect as string
    console.log('原始重定向URL:', redirect)
    
    // 修复重定向URL中可能包含的多个问号
    if (redirect && redirect.includes('?')) {
      const parts = redirect.split('?')
      if (parts.length > 1) {
        // 将第二个问号后的所有问号替换为&
        const newRedirect = parts[0] + '?' + parts.slice(1).join('&')
        console.log('修复重定向URL:', { 原始: redirect, 修复后: newRedirect })
        redirect = newRedirect
        
        // 使用修复后的URL替换查询参数
        const query = { ...to.query, redirect: newRedirect }
        next({ path: to.path, query })
        return
      }
    }
    
    // 验证重定向URL是否有效
    try {
      // 确保URL可以被正确解析
      new URL(redirect, window.location.origin)
    } catch (e) {
      console.error('无效的重定向URL:', redirect, e)
      const error = encodeURIComponent('重定向地址无效，请重新登录')
      next({ path: '/login', query: { error } })
      return
    }
  }
  
  // 已登录用户访问登录页时自动跳转到首页
  if (to.path === '/login' && isLoggedIn()) {
    console.log('用户已登录，自动跳转到首页')
    next('/')
    return
  }
  
  // 检查路由是否需要登录验证
  if (to.matched.some(record => record.meta.requiresAuth)) {
    // 如果需要登录验证，检查是否已登录
    const loggedIn = isLoggedIn()
    console.log('检查登录状态:', loggedIn, 'token:', localStorage.getItem('token'))
    
    if (!loggedIn) {
      console.log('未登录，重定向到登录页')
      // 未登录，重定向到登录页
      next({
        path: '/login',
        query: { redirect: to.fullPath } // 记录原目标路径，登录后可以重定向回去
      })
    } else {
      console.log('已登录，允许访问:', to.path)
      // 已登录，正常跳转
      next()
    }
  } else {
    console.log('不需要登录验证的页面:', to.path)
    // 不需要登录验证的页面，正常跳转
    next()
  }
})

// 全局路由错误处理
router.onError((error) => {
  console.error('路由错误:', error)
  
  // 检查是否是组件加载失败
  if (error.message && (
    error.message.includes('Failed to load') || 
    error.message.includes('Loading chunk') ||
    error.message.includes('Loading CSS chunk')
  )) {
    console.error('组件加载失败，重定向到首页')
    // 显示错误提示
    showToast({ 
      type: 'fail', 
      message: '页面加载失败，请稍后再试',
      position: 'bottom'
    })
    // 发生错误时重定向到首页
    router.replace('/')
  }
})

// 全局后置钩子
router.afterEach((to, from) => {
  console.log('路由跳转完成:', { from: from.path, to: to.path })
  // 清除加载状态或执行其他需要在路由完成后进行的操作
})

export default router 